;; ai-mode.el
;; Part 1: Create a new buffer and initialize it with a prompt.


;; 全局变量定义
(defvar ai-mode-api-url "http://api.tecorigin.com/v1/chat/completions"
  "The API endpoint for AI问答模式.")

(defvar ai-mode-api-key "YOUR TOKEN"
  "The API key for AI问答模式.")

(defvar ai-mode-model "deepseek-ai/DeepSeek-R1-Distill-Qwen-32B"
  "The model used for AI问答模式.")




(defvar ai-mode-buffer-name "*AI Chat*"
  "The name of the buffer for AI问答模式.")

(defun ai-mode--call-api (question)
  "Call the AI API with the given QUESTION and return the response."
  (let* ((url-request-method "POST")
         (url-request-extra-headers
          `(("Authorization" . ,ai-mode-api-key)
            ("Content-Type" . "application/json")))
         (url-request-data
	  (encode-coding-string 
          (json-encode
           `((model . ,ai-mode-model)
             (stream . :json-false)
             (messages . [((role . "user") (content . ,question))])))
           'utf-8)
	  )
         (buffer (url-retrieve-synchronously ai-mode-api-url)))
    (with-current-buffer buffer
      (goto-char (point-min))
      (re-search-forward "^$") ; 跳过 HTTP 头部
      (let*  ((json-string (decode-coding-string
                         (buffer-substring (point) (point-max))
                         'utf-8))

             (json-data (json-read-from-string
	      json-string))
             (choices (alist-get 'choices json-data))
             (first-choice (elt choices 0))
             (message (alist-get 'message first-choice))
             (content (alist-get 'content message)))
        (or content "Error: No response from API")))))

(defun ai-mode--insert-prompt (prompt)
  "Insert a prompt (e.g., 'Ask:') in the AI buffer."
  (goto-char (buffer-end 1))
  (insert (format "\n%s " prompt))
  (set-marker (point-marker) (point)))

(defun ai-mode--process-input()
  "process user input in the ai buffer"
  (interactive)
  (message "OK")
  (let ((input-start (save-excursion
                       (goto-char (line-beginning-position))
                       (search-forward "Ask: " nil t)
                       (point)))
        (input-end (line-end-position)))
        (message "line: %d %d" input-start input-end)
    (when (> input-end input-start) ; 确保用户输入了内容
      (let ((input (buffer-substring-no-properties input-start input-end)))
        (goto-char (buffer-end 1)) ; 移动光标到 buffer 末尾
        (ai-mode--insert-prompt "Answer:") ; 插入 "Answer:" 提示符
	(let ((answer (ai-mode--call-api (string-trim input))))
	  (insert answer))
        (set-marker (point-marker) (point)) ; 设置标记
        ;; (insert (format "User input: %s \n" input)) ; 打印用户输入到 buffer
        (ai-mode--insert-prompt "Ask:"))))) ; 插入新的 "Ask:" 提示符

(defun ai-mode--setup-buffer ()
  "Initialize the AI buffer and set up keybindings."
  (let ((buffer (get-buffer-create ai-mode-buffer-name)))
    (with-current-buffer buffer
      (erase-buffer) ; 清空 buffer 内容
      (insert "Welcome to AI问答模式!\n") ; 插入欢迎信息
      (ai-mode--insert-prompt "Ask:") ; 插入 "Ask:" 提示符
      (setq buffer-read-only nil) ; 设置 buffer 为可写状态
      (local-set-key (kbd "RET") 'ai-mode--process-input)) ; 绑定回车键
    buffer))


(defun ai-mode ()
  "Enter AI问答模式."
  (interactive)
  (let ((buffer (ai-mode--setup-buffer)))
    (switch-to-buffer buffer) ; 切换到 AI buffer
    (message "Switched to AI问答模式 buffer: %s" ai-mode-buffer-name)))

(provide 'ai-mode)
